import time
from datetime import datetime
from selenium import webdriver
from Django_Admin.settings import BASE_DIR

LOGIN_MAIL = "MAIL_ADDRESS"
LOGIN_PASSWORD = "PASSWORD"
ITEM_URL = "ITEM_URL"
ACCEPT_SHOP = 'Amazon'
LIMIT_VALUE = 33500    # 最低金额


def l(str):
    print("%s : %s" % (datetime.now().strftime("%Y/%m/%d %H:%M:%S"), str))


if __name__ == '__main__':

    # 启动
    try:
        b = webdriver.Chrome(BASE_DIR+'AutoLogin/chromedriver')
        b.get(ITEM_URL)
    except:
        l('Failed to open browser.')
        exit()

    while True:
        # 在库确认
        while True:
            try:
                shop = b.find_element_by_id('merchant-info').text
                shop = shop.split('卖')[0].split('商品')[1]

                if ACCEPT_SHOP not in shop:
                    raise Exception("not Amazon.")

                b.find_element_by_id('add-to-cart-button').click()
                break
            except:
                time.sleep(60)
                b.refresh()

        # 购买手续
        b.get('https://www.amazon.co.jp/gp/cart/view.html/ref=nav_cart')
        b.find_element_by_name('proceedToCheckout').click()

        # 检测是否登陆
        try:
            b.find_element_by_id('ap_email').send_keys(LOGIN_MAIL)
            b.find_element_by_id('ap_password').send_keys(LOGIN_PASSWORD)
            b.find_element_by_id('signInSubmit').click()
        except:
            l('LOGIN PASS.')
            pass

        # 值端确认
        p = b.find_element_by_css_selector('td.grand-total-price').text
        if int(p.split(' ')[1].replace(',', '')) > LIMIT_VALUE:
            l('金额设置过大.')
            continue

        # 注释确认
        b.find_element_by_name('placeYourOrder1').click()
        break

    l('ALL DONE.')
